package com.topscomm.mis.cbb.pm.service.abs;

import com.topscomm.basic.exception.ServiceException;
import com.topscomm.cbo.service.ICboItemDetailsService;
import com.topscomm.mis.cbb.pm.api.ITaskService;
import com.topscomm.mis.cbb.pm.api.IWbsService;
import com.topscomm.mis.cbb.pm.base.pojo.CbbPmProjectEntity;
import com.topscomm.mis.cbb.pm.base.service.impl.CbbPmProjectService;
import com.topscomm.mis.cbb.pm.base.service.impl.CbbPmTaskService;
//import com.topscomm.mis.cbb.pm.util.TaskTreeModel;
import com.topscomm.mis.cbb.pm.util.PmSystemConst;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.StringBufferProxy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@ConditionalOnMissingBean(ITaskService.class)
public abstract class AbstractWbsService implements IWbsService {
    @Autowired
    private CbbPmTaskService cbbPmTaskService;
    @Autowired
    private CbbPmProjectService cbbPmProjectService;
    @Autowired
    private ICboItemDetailsService cboItemDetailsService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void operateWbs(Map<String, Object> paraMap){
        return;
    };

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void changeWbs(Map<String, Object> paraMap){
        return;
    };

    /**
     * @author: hudeyong
     * @date: 2023-06-15
     * @description:创建wbs树
     * @modify:
     */
    @Override
    public List<Map<String, Object>> createWbsTreeList(Map<String, Object> paraMap) {
        String usercode = ConvertUtil.convertToString(paraMap.get("usercode"));
        if(!paraMap.containsKey("uuCode")) {
            throw new ServiceException("未找到对应WBS，请联系管理员！");
        }
        //WbsPublish
        String uuCode = ConvertUtil.convertToString(paraMap.get("uuCode"));
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle("code = '{0}'",uuCode);
        List<CbbPmProjectEntity> cbbPmProjectEntities = cbbPmProjectService.queryByWhere(sql.toString());
        if(cbbPmProjectEntities.size()==0){
            throw new ServiceException("未找到对应WBS，请联系管理员！");
        }
        String pmcode = cbbPmProjectEntities.get(0).getPmcode();
        String sourcetype = cbbPmProjectEntities.get(0).getType();
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("sourcetype",sourcetype);
        String deliveryStatus = PmSystemConst.CboYesNo.YES+"";
        List<Map<String, Object>> userList = cbbPmProjectService.queryMap(queryMap,"queryMaintainer");
        List<Map<String, Object>> tempList = userList.stream().filter(item -> ConvertUtil.convertToString(item.get("code")).equals(usercode)).collect(Collectors.toList());
        if (tempList.size()>0 || usercode.equals(pmcode)) {
            deliveryStatus += ","+PmSystemConst.CboYesNo.NO;
        }
        paraMap.put("deliveryStatus",deliveryStatus);
        List<Map<String, Object>> cbbPmTaskList = cbbPmTaskService.queryMap(paraMap,"queryWbsTask");
        cbbPmTaskService.setDispFields(cbbPmTaskList);
//        TaskTreeModel taskTreeModel = new TaskTreeModel();
        List<Map<String, Object>> treeList = buildTree(cbbPmTaskList, false, "");
        putWbsTreeListIndex(treeList,1,"");
        return treeList;
    }

    public List<Map<String, Object>> buildTree(List<Map<String, Object>> taskList, boolean isAddRoot, String rootName) {
        // 如果支持根节点，则增加默认根节点
        if (isAddRoot == true) {
            Map<String, Object> rootMap = new HashMap<String, Object>();
            rootMap.put("code", "0");
            rootMap.put("pcode", "-1");
            rootMap.put("name", rootName);
            taskList.add(rootMap);
        }
        // 构建上下级的树节点
        List<Map<String, Object>> treeList = new ArrayList<>();
        // 构建节点
        for (Map<String, Object> tempMap : taskList) {
            if (ConvertUtil.convertToString(tempMap.get("code")).length() <= 1) {
                treeList.add(tempMap);
                continue;
            }
            boolean haveParent = false;
            for (Map<String, Object> parentTask : taskList) {
                if (ConvertUtil.convertToString(tempMap.get("parentcode"))
                        .equals(ConvertUtil.convertToString(parentTask.get("code")))) {
                    if (!parentTask.containsKey("children")) {
                        parentTask.put("children", new ArrayList<Map<String, Object>>());
                    }
                    List<Map<String, Object>> chrildrenList = (List<Map<String, Object>>) parentTask.get("children");
                    chrildrenList.add(tempMap);
                    parentTask.put("children", chrildrenList);
                    haveParent = true;
                    break;
                }
            }
            if (haveParent == false) {
                treeList.add(tempMap);
            }
        }
        return treeList;
    }

    /**
     * @author: hudeyong
     * @date: 2023-06-19
     * @description:添加等级
     * @modify:
     */
    public void putWbsTreeListIndex(List<Map<String, Object>> cbbPmTaskList, int level, String initIndex){
        int index = 1;
        for(Map<String, Object> task : cbbPmTaskList){
            String newInitIndex = level==1 ? index+"" : initIndex+"."+index;
            task.put("level", level);
//            task.setLevel(level);
            List<Map<String, Object>> childrenTaskList = (List<Map<String, Object>>) task.get("children");
            if(childrenTaskList!=null){
                putWbsTreeListIndex(childrenTaskList, level + 1,newInitIndex);
            } else {
                task.put("children", new ArrayList<Map<String, Object>>());
//                task.setChildren(new ArrayList<>());
            }
            index++;
        }
    }
}
